//
//  KKLiveChatToolBarView.m
//  KKLiveDemo
//
//  Created by leo on 2017/7/29.
//  Copyright © 2017年 leo. All rights reserved.
//

#import "KKLiveChatToolBarView.h"
#import "KKLiveHelper.h"

@interface KKLiveChatToolBarView() {
    
    CGFloat _previousTextViewContentHeight;//上一次inputTextView的contentSize.height
}

@end

@implementation KKLiveChatToolBarView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        
        self.backgroundColor = [UIColor whiteColor];
        CGFloat pointY = (CGRectGetHeight(frame) - 40)/2.0;
        
        _otherTextField = [[UITextField alloc] initWithFrame: CGRectZero];
        [self addSubview: _otherTextField];
        
        _btn_switch = [UIButton buttonWithType: UIButtonTypeCustom];
        _btn_switch.frame = CGRectMake(0, pointY, 40, 40);
        _btn_switch.backgroundColor = [UIColor clearColor];
        _btn_switch.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [_btn_switch setTitle: @"" forState: UIControlStateNormal];
        [_btn_switch setImage: [KKLiveHelper kk_chatImageWithName: @"chat_toolbar_voice_nor"] forState: UIControlStateNormal];
        [_btn_switch setImage: [KKLiveHelper kk_chatImageWithName: @"chat_toolbar_keyboard_nor"] forState: UIControlStateSelected];
        [_btn_switch setBackgroundImage: [UIImage new] forState: UIControlStateSelected];
        [_btn_switch addTarget: self action: @selector(action_switch:) forControlEvents: UIControlEventTouchUpInside];
        [self addSubview: _btn_switch];
        
        _btn_more = [UIButton buttonWithType: UIButtonTypeSystem];
        _btn_more.frame = CGRectMake(CGRectGetWidth(frame)-40, pointY, 40, 40);
        _btn_more.tintColor = [UIColor darkGrayColor];
        _btn_more.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [_btn_more setTitle: @"" forState: UIControlStateNormal];
        [_btn_more setImage: [KKLiveHelper kk_chatImageWithName: @"chat_toolbar_more_nor"] forState: UIControlStateNormal];
        [_btn_more addTarget: self action: @selector(action_more:) forControlEvents: UIControlEventTouchUpInside];
        [self addSubview: _btn_more];
        
        _btn_gifEmoticon = [UIButton buttonWithType: UIButtonTypeSystem];
        _btn_gifEmoticon.frame = CGRectMake(CGRectGetMinX(_btn_more.frame) - 45, pointY, 40, 40);
        _btn_gifEmoticon.tintColor = [UIColor lightGrayColor];
        _btn_gifEmoticon.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [_btn_gifEmoticon setTitle: @"" forState: UIControlStateNormal];
        [_btn_gifEmoticon setImage: [KKLiveHelper kk_chatImageWithName: @"chat_toolbar_gif_nor"] forState: UIControlStateNormal];
        [_btn_gifEmoticon addTarget: self action: @selector(action_gif:) forControlEvents: UIControlEventTouchUpInside];
        [self addSubview: _btn_gifEmoticon];
        
        _btn_emoticon = [UIButton buttonWithType: UIButtonTypeSystem];
        _btn_emoticon.frame = CGRectMake(CGRectGetMinX(_btn_gifEmoticon.frame) - 45, pointY, 40, 40);
        _btn_emoticon.tintColor = [UIColor darkGrayColor];
        _btn_emoticon.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [_btn_emoticon setTitle: @"" forState: UIControlStateNormal];
        [_btn_emoticon setImage: [KKLiveHelper kk_chatImageWithName: @"chat_toolbar_smile_nor"] forState: UIControlStateNormal];
        [_btn_emoticon addTarget: self action: @selector(action_emotion:) forControlEvents: UIControlEventTouchUpInside];
        [self addSubview: _btn_emoticon];
        
        __weak typeof(self) weakSelf = self;
        _chatTextView = [[KKChatTextView alloc] initWithFrame: CGRectMake(CGRectGetMaxX(_btn_switch.frame) + 5, pointY + 4, CGRectGetMinX(_btn_emoticon.frame) - CGRectGetMaxX(_btn_switch.frame) - 5, CGRectGetHeight(self.bounds) - 18)];
        _chatTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _chatTextView.changeContentHeightHandle = ^(CGFloat height){
            
            CGFloat contentHeight = height;
            
            if (height > 100) {
                contentHeight = 105;
            }
            else if (height < 50) {
                contentHeight = 50;
            }
            else {
                contentHeight = height + 7;
            }
//            weakSelf.layout_heightValue.constant = height + 7;
            NSLog(@"self.center = %@ | %@", [NSValue valueWithCGPoint: weakSelf.center], @(contentHeight));
            _previousTextViewContentHeight = contentHeight;
            [weakSelf private_updateToolBarHeight: contentHeight];
        };
        _chatTextView.didEndEditTextHandle = ^(NSString *text) {
            
        };
        [self addSubview: _chatTextView];
        
        _btn_voice = [UIButton buttonWithType: UIButtonTypeSystem];
        _btn_voice.frame = CGRectMake(CGRectGetMaxX(_btn_switch.frame) + 5, pointY + 4, CGRectGetMinX(_btn_emoticon.frame) - CGRectGetMaxX(_btn_switch.frame) - 5, 32);
        _btn_voice.backgroundColor = [UIColor whiteColor];
        _btn_voice.layer.cornerRadius = 3.0;
        _btn_voice.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _btn_voice.layer.borderWidth = 0.5;
        _btn_voice.tintColor = [UIColor darkGrayColor];
        _btn_voice.hidden = YES;
        [_btn_voice setTitle: @"按住 说话" forState: UIControlStateNormal];
        [_btn_voice setTitle: @"松开 结束" forState: UIControlStateHighlighted];
        [_btn_voice addTarget: self action: @selector(action_startRecorder:) forControlEvents: UIControlEventTouchDown];
        [_btn_voice addTarget: self action: @selector(action_stopRecorder:) forControlEvents: UIControlEventTouchUpInside];
        [self addSubview: _btn_voice];
        
        UIColor *lineColor = [UIColor colorWithRed:208/255.0 green:207/255.0 blue:223/255.0 alpha:1.0];
        UIView *topLineView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, CGRectGetWidth(frame), 1)];
        topLineView.backgroundColor = lineColor;
        [self addSubview: topLineView];
        UIView *bottomLineView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, CGRectGetWidth(frame), 1)];
        bottomLineView.backgroundColor = lineColor;
        [self addSubview: bottomLineView];
        
        [self init_emotionViewUI];
        [self init_functionViewUI];
    }
    return self;
}

#pragma mark - Overrider methods
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (![self pointInside: point withEvent: event]) {
        if ([self.chatTextView isFirstResponder] || [self.otherTextField isFirstResponder]) {
            [self.chatTextView resignFirstResponder];
            [self.otherTextField resignFirstResponder];
        }
    }
    return [super hitTest: point withEvent: event];
}

#pragma mark - Init methods
- (void)init_emotionViewUI {
    
    __weak typeof(self) weakSelf = self;
    self.emoticonView = [KKChatEmoticonView kk_chatEmoticonViewWithItems: @[]];
    self.emoticonView.didSelectedHandle = ^(NSInteger image_index, UIImage *image){
        [weakSelf.chatTextView kk_appendEmoticonImageIndex: image_index];
    };
    self.emoticonView.didSendHandle = ^{
        NSAttributedString *coreText = weakSelf.chatTextView.attributedText;
        [weakSelf.chatTextView kk_cleanAllText];
//        [weakSelf im_sendCoreTextMessageWithMessageText: coreText];
    };
    
    self.gifEmoticonView = [KKCHatGifEmoticonView kk_chatGifEmoticonViewWithItems: @[]];
    self.gifEmoticonView.didSelectedHandle = ^(NSInteger image_index, NSString* imagePath){
        
//        [weakSelf im_sendGifFaceMessageWithGifImagePath: imagePath];
    };
}

- (void)init_functionViewUI {
    
//    __weak typeof(self) weakSelf = self;
//    KKImagePickerManager *imagePickerManager = [KKImagePickerManager kk_defaultManager];
//    imagePickerManager.maxLimit = 1;
//    imagePickerManager.resultBlock = ^(NSArray *images){
//        UIImage *targetImage = [images firstObject];
//        [weakSelf im_sendPictureMessageWithImage: targetImage];
//    };
    
    NSMutableArray *functionItems = [NSMutableArray array];
    {
        KKChatFunctionItem *photoItem = [KKChatFunctionItem kk_itemOfTitle: @"拍照" itemImage: [KKLiveHelper kk_chatImageWithName: @"chat_function_photo"] selectedEventHandle:^{
            
//            if (![weakSelf private_checkSelfStatus]) {
//                return;
//            }
//            
//            [[KKImagePickerManager kk_defaultManager] kk_takePictureFromCamera];
        }];
        [functionItems addObject: photoItem];
        
        KKChatFunctionItem *pictureItem = [KKChatFunctionItem kk_itemOfTitle: @"照片" itemImage: [KKLiveHelper kk_chatImageWithName: @"chat_function_picture"] selectedEventHandle:^{
            
//            if (![weakSelf private_checkSelfStatus]) {
//                return;
//            }
//            
//            [[KKImagePickerManager kk_defaultManager] kk_takePictureFromAlbum];
        }];
        [functionItems addObject: pictureItem];
        
        /*  暂时不使用语音电话
         KKChatFunctionItem *voiceItem = [KKChatFunctionItem kk_itemOfTitle: @"语音" itemImage: [UIImage kk_chatImageWithName: @"chat_function_voice"] selectedEventHandle:^{
         [self im_sponsorVoiceChat];
         }];
         [functionItems addObject: voiceItem];
         */
    }
    
    self.functionView = [KKChatFunctionView kk_chatFunctionViewWithItems: functionItems];
}

#pragma mark - Action methods
- (void)action_switch:(id)sender {
    
    if (self.btn_switch.isSelected) {
        self.btn_switch.selected = false;
        self.btn_voice.hidden = YES;
        self.chatTextView.hidden = NO;
        self.chatTextView.inputView = nil;
        [self.chatTextView reloadInputViews];
        [self.chatTextView becomeFirstResponder];
        [self private_updateToolBarHeight: _previousTextViewContentHeight];
    }
    else {
        self.btn_switch.selected = true;
        self.btn_voice.hidden = NO;
        self.chatTextView.hidden = YES;
        [self.chatTextView resignFirstResponder];
        [self.otherTextField resignFirstResponder];
        [self private_updateToolBarHeight: 50.0];
    }
}

- (void)action_emotion:(id)sender {
    
    self.btn_switch.selected = false;
    self.btn_voice.hidden = YES;
    
    self.otherTextField.inputView = self.emoticonView;
    [self.otherTextField reloadInputViews];
    [self.otherTextField becomeFirstResponder];
}

- (void)action_gif:(id)sender {
    
    self.btn_switch.selected = false;
    self.btn_voice.hidden = YES;
    
    self.otherTextField.inputView = self.gifEmoticonView;
    [self.otherTextField reloadInputViews];
    [self.otherTextField becomeFirstResponder];
}

- (void)action_more:(id)sender {
    
    self.btn_switch.selected = false;
    self.btn_voice.hidden = YES;
    
    self.otherTextField.inputView = self.functionView;
    [self.otherTextField reloadInputViews];
    [self.otherTextField becomeFirstResponder];
}

- (void)action_startRecorder:(id)sender {
    NSLog(@"开始录音");
//    //  开始录音
//    [[KKAudioManager sharedManager] startRecorder:^(NSTimeInterval timeInterval) {
//        NSLog(@"录音时间...%@",@(timeInterval));
//    }];
}

- (void)action_stopRecorder:(id)sender {
    //  结束录音
    NSLog(@"结束录音");
    __weak typeof(self) weakSelf = self;
//    [[KKAudioManager sharedManager] stopRecorder:^(NSString *audioFilePath, NSTimeInterval duration, NSString *error) {
//        NSLog(@"audioFilePath...%@|%@",audioFilePath,@(duration));
//        if (duration >= 1.0) {
//            [weakSelf im_sendVoiceMessageWithAudioPath: audioFilePath audioSecond: (NSInteger)duration];
//        }
//        else {
//            [SVProgressHUD showErrorWithStatus: @"录音时间太短"];
//        }
//    }];
    
    if (self.delegate && [self.delegate respondsToSelector: @selector(liveChatToolBarDidSendMsg:)]) {
//        KKMessageItem *messageItem = [KKMessageItem msgWithText: @"sdfasdfdsafdsfd"];
        KKMessageItem *messageItem = [KKMessageItem msgWithDate: [NSDate date]];
        [self.delegate liveChatToolBarDidSendMsg: messageItem];
    }
    
}

#pragma mark - Private methods
- (void)private_updateToolBarHeight:(CGFloat)height {
    
    self.frame = CGRectMake(CGRectGetMinX(self.frame), CGRectGetMinY(self.frame), CGRectGetWidth(self.bounds), height);
    [self layoutIfNeeded];
    
    if (self.delegate && [self.delegate respondsToSelector: @selector(liveChatToolBarDidUpdateBarHeight:)]) {
        [self.delegate liveChatToolBarDidUpdateBarHeight: height];
    }
}

@end
